#include "cmdlib.h"
#include <sys/types.h>
//#include <sys/dir.h>
#include <dirent.h>


typedef struct
{
	char	name[56];
	int		filepos, filelen;
} packfile_t;

typedef struct
{
	char	id[4];
	int		dirofs;
	int		dirlen;
} packheader_t;

packfile_t	pfiles[4096];
int		h, i, d;
packheader_t	header;
packfile_t	*pf;

int	dirnamelen;

void PackDirectory (char *dir)
{
	void		*buffer;
#ifdef NeXT
	struct direct **namelist, *ent;
#else
	struct dirent **namelist, *ent;
#endif
	int		count;
	struct stat st;
	int			i;
	int			len;
	char		newdir[1024];
	char		fullname[1024];
	char		*name;

	count = scandir(dir, &namelist, NULL, NULL);

	for (i=0 ; i<count ; i++)
	{
		ent = namelist[i];
		name = ent->d_name;

		if (name[0] == '.')
			continue;
		strcpy (fullname, dir);
		strcat (fullname, "/");
		strcat (fullname, name);
		strcpy (pf->name, fullname + dirnamelen);

		if (stat (fullname, &st) == -1)
			Error ("fstating %s", pf->name);
		if (st.st_mode & S_IFDIR)
		{	// directory
			strcpy (newdir, fullname);
			PackDirectory (newdir);
			continue;
		}

		len = LoadFile (fullname, &buffer);
		pf->filepos = LittleLong (lseek (h, 0, SEEK_CUR));
		pf->filelen = LittleLong(len);

		SafeWrite (h, buffer, len);
		free (buffer);
		printf ("%64s : %6i\n", pf->name, len);
		pf++;

	}
}

int main (int argc, char **argv)
{
	int		dirlen;
	char	outname[1024];

	if (argc != 3)
		Error ("usage: dirpack <directory> <fileName>.pak");

	sprintf (outname, "%s", argv[2]);

	h = SafeOpenWrite (outname);
	SafeWrite (h, &header, sizeof(header));

	pf = pfiles;

	dirnamelen = strlen(argv[1]) + 1;
	PackDirectory (argv[1]);

	header.id[0] = 'P';
	header.id[1] = 'A';
	header.id[2] = 'C';
	header.id[3] = 'K';
	dirlen = (byte *)pf - (byte *)pfiles;
	header.dirofs = LittleLong(lseek (h, 0, SEEK_CUR));		// location of packfiles
	header.dirlen = LittleLong(dirlen);

	SafeWrite (h, pfiles, dirlen);

	i = (int)lseek (h, 0, SEEK_CUR);

	lseek (h, 0, SEEK_SET);
	SafeWrite (h, &header, sizeof(header));
	close (h);

	d = pf - pfiles;
	printf ("%i files packed in %i bytes\n",d, i);
    return 0;
}
